'use strict'
import axios, {
  AxiosError,
  AxiosInstance,
  AxiosResponse,
  CreateAxiosDefaults,
} from 'axios'
import 'element-plus/theme-chalk/el-notification.css'
import { hideLoading } from '@/plugins/loading'
import useUserStore from '@/stores/user'
import { REMOVE_TOKEN } from '@/plugins/util'
import router from '@/router'
import { Message } from '@/hooks/message'

const config: CreateAxiosDefaults = {}

const _axios: AxiosInstance = axios.create(config)

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    const userStore = useUserStore()
    if (userStore.satoken) {
      config.headers.Authorization = userStore.satoken
    }
    return config
  },
  function (error: AxiosError<Result>) {
    // Do something with request error
    Message({
      message: error.response?.data.message || error.message,
      type: 'error',
    })
    hideLoading()
    return Promise.reject(error)
  },
)

_axios.interceptors.response.use(
  function (response: AxiosResponse<Result>) {
    const { data, status } = response
    if (status !== 200) {
      Message({
        message: data.message,
        type: 'error',
      })
    }
    return response
  },
  function (error: AxiosError<Result>) {
    // Do something with response error
    hideLoading()
    if (error.request.responseURL.indexOf('/bing/') !== -1) {
      return Promise.reject(error)
    }

    if (error.response?.data.status === 401) {
      REMOVE_TOKEN()
      const userStore = useUserStore()
      userStore.clearUser()
      if (router.currentRoute.value.path !== '/login') {
        window.location.href =
          import.meta.env.BASE_URL +
          '/login' +
          '?redirect=' +
          router.currentRoute.value.fullPath
      }

      return Promise.reject(error)
    }

    Message({
      message: error.response?.data.message || error.message,
      type: 'error',
    })

    return Promise.reject(error)
  },
)

export interface Result<T = any> {
  status: number
  message: string
  data: T
}

export default _axios
